var smetkiArray = new Array();
var editmode = 0;
var categorii = new Array();
var mappingsArray = new Array();
var chartArray = Array();
var firstTimer = 0;
var balans = 0;
var income = 0;

String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

function cellHtml(cell_data, index, edit, edit_class, id){
	var result = '';
	if (edit == 1){
		result += '<td id="'+id+'" class="t'+index+' '+edit_class+'">';
	} else {
		result += '<td class="t'+index+'">';
	}
	result += cell_data;
	result += '</td>';
	return result;
}

function list_smetki(table){
	var result = '<table class="add-razhod">';
	//result += '<tr>';
	//HEADER
	//result += '</tr>';
	balans = 0;
	income = 0;
	withdrawn = 0;
	var flag = 0;
	var outgoing = 0;
	for(i=0; i<table.length;i++){
		var chetnost = 'odd';
		var income1 = table[i][6] == 0?'':' prihod';
		if (flag == 1) {
			chetnost = 'even';
		}
		result += '<tr class="'+chetnost+income1+'">';
		result += cellHtml(table[i][1],1,editmode,'edit_date datepicker', table[i][0]);
		result += cellHtml(table[i][2],2,editmode,'edit_descr', table[i][0]);
		result += cellHtml(table[i][3],3,editmode,'edit_sum', table[i][0]);
		result += cellHtml(table[i][4],4,editmode,'edit_comment', table[i][0]);
		result += cellHtml(table[i][5],5,editmode,'edit_category', table[i][0]);
		var kindA = 'изтеглени';
		if (table[i][6] == 0){
			kindA = 'разход';
		} else if (table[i][6] == 1){
			kindA = 'приход';
		} 
		result += cellHtml(kindA,6,editmode,'edit_type', table[i][0]);
		if (editmode == 1) {
			result += '<td>';
			result += '<input class="table-submit" type="button" value="изтрий" name="Remove" onclick="deleteLine(\''+table[i]+'\')"></input>';
			result += '</td>';
		}
		result += '</tr>';
		if (table[i][6] == 0){
			outgoing = outgoing + parseFloat(table[i][3]);	
		} else if (table[i][6] == 1){
			income = income + parseFloat(table[i][3]);
		} else if (table[i][6] == 2){
			withdrawn = withdrawn + parseFloat(table[i][3]);
		}
		if (flag == 0){
			flag = 1;
		} else {
			flag = 0;
		}

	}
	balans = income - outgoing;

	result += '</table>';
	var resultB = '<p>Похарчени: '+'<span class="bold">'+outgoing.toFixed(2)+'</span>'+'</p>';
	resultB += '<p>Придобити: '+'<span class="bold">'+income.toFixed(2)+'</span>'+'</p>';
	resultB += '<p>Изтеглени: '+'<span class="bold">'+withdrawn.toFixed(2)+'</span>'+'</p>';
	resultB += '<p>Баланс: '+'<span class="bold">'+balans.toFixed(2)+'</span>'+'</p>';
	document.getElementById("realcontent").innerHTML = result;
	document.getElementById("balans").innerHTML = resultB;
	generateHelperArray(table);
	enableEditable();
}

function list_table_smetki(table){
	if (table.length == 0){
		document.getElementById("realcontent").innerHTML = '';
		return;
	}
	smetkiArray = table;
	if(document.getElementById("find").value == ""){
		list_smetki(table);
	} else {
		filterSmetki();
	}
}

function filterSmetki(){
	var filter = trim(document.getElementById("find").value).toLowerCase();
	var result = new Array();
	var j = 0;
	for(i=0; i<smetkiArray.length;i++){
		if(filter.startsWith('-')){
			if (filter.length == 1){
				result[j++] = new Array(smetkiArray[i][0],smetkiArray[i][1],smetkiArray[i][2],smetkiArray[i][3],smetkiArray[i][4],smetkiArray[i][5],smetkiArray[i][6]);
			} else {
				var filter2 = filter.substr(1, filter.length);
				if (smetkiArray[i][2].toLowerCase().indexOf(filter2) == -1 && 
						smetkiArray[i][1].toLowerCase().indexOf(filter2) == -1 &&
						smetkiArray[i][3].toLowerCase().indexOf(filter2) == -1 &&
						smetkiArray[i][4].toLowerCase().indexOf(filter2) == -1 && 
						smetkiArray[i][5].toLowerCase().indexOf(filter2) == -1 &&
						isKindOfTransaction(smetkiArray[i][6], filter2)){
					result[j++] = new Array(smetkiArray[i][0],smetkiArray[i][1],smetkiArray[i][2],smetkiArray[i][3],smetkiArray[i][4],smetkiArray[i][5],smetkiArray[i][6]);
				}
			}
		} else if (smetkiArray[i][2].toLowerCase().indexOf(filter) != -1 || 
				smetkiArray[i][1].toLowerCase().indexOf(filter) != -1 ||
				smetkiArray[i][3].toLowerCase().indexOf(filter) != -1 ||
				smetkiArray[i][4].toLowerCase().indexOf(filter) != -1 || 
				smetkiArray[i][5].toLowerCase().indexOf(filter) != -1 ||
				isKindOfTransaction(smetkiArray[i][6], filter)){
			result[j++] = new Array(smetkiArray[i][0],smetkiArray[i][1],smetkiArray[i][2],smetkiArray[i][3],smetkiArray[i][4],smetkiArray[i][5],smetkiArray[i][6]);
		}
	}
	list_smetki(result,0);
}

function isKindOfTransaction(kind, filter2){
	var kindA = 'изтеглени'; 
	if (kind == 0){
		kindA = 'разход';
	} else if (kind == 1){
		kindA = 'приход';
	} 
//	alert(kindA);
//	alert(filter2);
//	alert(kindA.indexOf(filter2));
	return kindA.indexOf(filter2) != -1;
}


function setEditMode(){
	if(document.getElementById('editbutton').value == 'редактиране'){
		document.getElementById('editbutton').value = 'айде';
		editmode = 1;
		list_smetki(smetkiArray);
	} else {
		document.getElementById('editbutton').value = 'редактиране';
		editmode = 0;
		list_smetki(smetkiArray);
//		agent.call('','getSmetki','list_table_smetki');
	}
}

function setEditModeDone(){
	if(document.getElementById('editbutton').value = 'айде'){
		document.getElementById('editbutton').value = 'редактиране';
	}
}

function setCategories(cats){
	categorii = cats;
}


function enableEditable(){
	$('.edit_descr').editable('smetki/save_smetki.php',{
		id   : 'descr_id',
		name : 'newvalue',
		type      : 'text',
		submit    : 'OK',
		tooltip   : 'Цък за да редактираш...'
	});
	$('.edit_date').editable('smetki/save_smetki.php',{
		id   : 'date_id',
		name : 'newvalue',
		type      : 'text',
		submit    : 'OK',
		tooltip   : 'Цък за да редактираш...'
	});

	$('.edit_comment').editable('smetki/save_smetki.php',{
		id   : 'comment_id',
		name : 'newvalue',
		type      : 'text',
		submit    : 'OK',
		tooltip   : 'Цък за да редактираш...'
	});

	$('.edit_sum').editable('smetki/save_smetki.php',{
		id   : 'sum_id',
		name : 'newvalue',
		type      : 'text',
		submit    : 'OK',
		tooltip   : 'Цък за да редактираш...'
	});

	$('.edit_type').editable('smetki/save_smetki.php',{
		id   : 'type_id',
		name : 'newvalue',
		data : {'0':'разход','1':'приход', '2':'изтеглени'},
		type      : 'select',
		submit    : 'OK',
		tooltip   : 'Цък за да редактираш...'
	});
	$('.edit_category').editable('smetki/save_smetki.php',{
		id   : 'categ_id',
		name : 'newvalue',
		data : categorii,
		type      : 'select',
		submit    : 'OK',
		tooltip   : 'Цък за да редактираш...'
	});
//	$(".datepicker").datepicker({ dateFormat: 'yy-mm-dd'});
}

function changeDate(catName){
	agent.call('','getEntriesByDate','list_table_smetki', catName);
	generateCategries_o(null, catName, 'changeDate');
}

function addLine() {
	agent.call('','saveLine', 'list_table_smetki', document.getElementById('datepicker').value,
			document.getElementById('descr').value,
			document.getElementById('sum').value,
			document.getElementById('comment').value,
			document.getElementById('categories').value,
			document.getElementById('sType').value, 
			selectedCategoryField.toString())
			var currentTime = new Date();
	document.getElementById('datepicker').value = currentTime.getFullYear()+'-'+(currentTime.getMonth()+1)+'-'+currentTime.getDate();
	document.getElementById('descr').value = 'описание';
	document.getElementById('sum').value = 'сума';
	document.getElementById('comment').value = 'допълнителен коментар';
	document.getElementById('sType').value = '0';
	clearTimeout(refreshSchedule);
}


function deleteLine(id){
	agent.call('','removeLine', 'list_table_smetki', id, selectedCategoryField.toString());
	clearTimeout(refreshSchedule);
}

function generateHelperArray(table1){
	var index = -1;
	var j = 0;
	chartArray = Array();
	if(table1.length == 0){
		chartArray[0] = new Array('empty', 100); 
	}
			
	for(k=0; k<table1.length;k++){
		if(table1[k][6] != 0){
			continue;
		}
		index = getTableIndex(chartArray, table1[k][5]);
		if (index == -1){
			chartArray[j++] = new Array(table1[k][5], table1[k][3]);
		} else {
			chartArray[index][1] = parseFloat(chartArray[index][1]) + parseFloat(table1[k][3]);
		}
	}
}

function getTableIndex(table, missing){
	for(i=0; i<table.length;i++){
		if (table[i][0] == missing){
			return i;
		}
	}
	return -1;
}

function show_hide_charts(){
	if (document.getElementById("hiddentable").style.display != 'none'){
		document.getElementById("hiddentable").style.display = 'none';
	} else {
		document.getElementById("hiddentable").style.display = 'block';
		newChartDraw();
	}
}


function newChartDraw(){
	drawBalans();
	drawspendings();
	
}

function drawspendings(){
	if (chartArray.length == 0){
		return;
	}
	var data = new google.visualization.DataTable();
	data.addColumn('string', 'Категория');
	data.addColumn('number', 'сума');
	data.addRows(chartArray.length);
	for(i=0; i<chartArray.length;i++){
		data.setValue(i, 0, chartArray[i][0]);
		data.setValue(i, 1, parseFloat(chartArray[i][1]));

	}
	
	var chart = new google.visualization.PieChart(document.getElementById('spendingsChart'));
	chart.draw(data, {width: 400, height: 240, titleFontSize: 15, is3D: true, title: 'Разходи'});
}

function drawBalans(){
	
	var data = new google.visualization.DataTable();
	data.addColumn('string', 'Баланс');
	data.addColumn('number', 'сума');
	data.addRows(1);
	data.setValue(0, 0, 'Баланс');
	if (balans < 0){
		data.setValue(0, 1, 0);
		
	} else {
		data.setValue(0, 1, Math.round(balans*100)/100);
	}
	var chartDiv = document.getElementById('balansChart');
	var options = {title: 'Налични'};
    var chart = new PilesOfMoney(chartDiv);
    chart.draw(data, options);
}

function setMatchMap(mappings){
	mappingsArray = mappings;
}

function setCategoryArtificialy(){
	var lstring = document.getElementById('descr').value;
	for(i=0; i<mappingsArray.length;i++){
		if (lstring == mappingsArray[i][0]){
			Select_Value_Set('categories', mappingsArray[i][1]);
			break;
		}
		
	}
}

function Select_Value_Set(SelectName, Value) {
		var SelectObject = document.getElementById('categories');
	  for(index = 0; 
	    index < SelectObject.length; 
	    index++) {
		  
	   if(SelectObject[index].value == Value) {
	     SelectObject.selectedIndex = index;
	   }
	   }
	}

function refreshForced(){
	agent.call('','getLastEntriesByDate','list_table_smetki');
}






